<?php
class system_paginator implements Countable, IteratorAggregate {
	protected $_adapter;
	protected $_pageRange = 10;
	
	public function __construct(system_paginator_adapter_interface $adapter) {
		$this->_adapter = $adapter;
	}
	
	//得到第一页的号码
	public function getFirst() {
		return 1;
	}
	//得到最后一页的号码
	public function getLast() {
		return (int) $this->getPageCount();
	}
	
	//得到上一页的号码
	public function getPrevious() {
		if($this->getCurrentPageNumber()-1>0) {
			return $this->getCurrentPageNumber()-1;
		} else {
			return null;
		}
	}
	//得到下一页的号码
	public function getNext() {
		if($this->getCurrentPageNumber()+1<$this->getPageCount()) {
			return $this->getCurrentPageNumber()+1;
		} else {
			return null;
		}
	}
	
	//得到当前页面的第一条数据的编号位置 
	public function getFirstItemNumber() {
		return $this->getCurrentPageNumber()*$this->getLimit()-$this->getLimit()+1;
	}
	//得到当前页最后一条数据的编号位置
	public function getLastItemNumber() {
		return $this->getCurrentPageNumber()*$this->getLimit()-($this->getLimit()-($this->getLimit()-$this->getCurrentItemCount()));
	}
	
	public function getFirstPageInRange() {
		$half = ($this->getPageRange()/2);
		if($this->getCurrentPageNumber()-$half>=$this->getFirst()) {
			return $this->getCurrentPageNumber()-$half;
		} else {
			return $this->getFirst();
		}
	}
	public function getLastPageInRange() {
		$half = ($this->getPageRange()/2);
		
		if($this->getCurrentPageNumber()<=$half) {
			return ($this->getPageRange()+1)>$this->getLast() ? $this->getLast() : ($this->getPageRange()+1);
		}
		
		if($this->getCurrentPageNumber()+$half<=$this->getLast()) {
			return $this->getCurrentPageNumber()+$half;
		} else {
			return $this->getLast();
		}
	}
	//反回当前分页的列表数组
	public function getPagesInRange() {
		$list = array();
		//var_dump($this->getLastPageInRange());exit;
		for($i = $this->getFirstPageInRange(); $i<=$this->getLastPageInRange(); $i++) {
			$list[] = $i;
		}
		return $list;
	}
	
	public function getAdapter() {
		return $this->_adapter;
	}
	
	public function getPageCount() {
		return ceil($this->getItemCount()/$this->getLimit());
	}
	
	public function getLimit() {
		return $this->_adapter->getLimit();
	}
	
	public function setPageRange($range) {
		$this->_pageRange = $range;
		return $this;
	}
	public function getPageRange() {
		return ($this->_pageRange%2==0) ? $this->_pageRange : $this->_pageRange-1;
	}
	
	public function getCurrentPageNumber() {
		return $this->_adapter->getCurrentPageNumber();
	}
	
	//数据总数
	public function getItemCount() {
		return $this->_adapter->getTotal();
	}
	
	public function getCurrentItemCount() {
		return $this->count();
	}
	public function count() {
		return count($this->getIterator());
	}
	
	public function getIterator() {
		return $this->_adapter->getItem();
	}

}